#! /usr/bin/env node

const path = require('path');
const fs = require('fs');
const http = require('http');
const args = process.argv.slice(2);
let PORT = 8080;


if(args.length == 0){ // 没有参数
    createServe();
} else {
    if(args[0] == '-v'){
        console.log('版本号是1.0.0');
    } else if(args[0] == '-p') {
        PORT = args[1]; // 修改端口号
        createServe();
    }
}


function createServe() {
    http.createServer((req, res)=>{
        // res.setHeader('Content-Type', 'application/json');
        console.log(req.url);

        if(req.url === '/favicon.ico'){
            return res.end('404');
        }

        let rootPath = process.cwd();
        rootPath = path.join(rootPath, req.url);
        if(fs.existsSync(rootPath)) {
            if(fs.statSync(rootPath).isDirectory()) {
                let html = fs.readFileSync(path.join(__dirname, './public/index.html'), 'utf8');
                const dir = fs.readdirSync(rootPath);
                const text = dir.map((item) => {
                    return `<li>
                        <a href="${path.join(req.url, item)}">${item}</a>
                    </li>`
                }).join('')
                html = html.replace('{{list}}', text);
                console.log(html);
                return res.end(html);
            } else {
                console.log('是文件');
                return res.end(fs.readFileSync(rootPath));
            }
        } else {
            return res.end('NOT FOUND');
        }
        // res.end('200 测试数据');
    }).listen(PORT, ()=>{ console.log('启动成功'); });
}